package com.monkey.netty.chapter5;

import java.util.concurrent.TimeUnit;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class OutBoundDemo {

	public static void main(String[] args) {
		ServerBootstrap serverBootstrap = new ServerBootstrap();
		NioEventLoopGroup bossGroup = new NioEventLoopGroup();
		NioEventLoopGroup workerGroup = new NioEventLoopGroup();
		serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
				.option(ChannelOption.SO_BACKLOG, 1024).childOption(ChannelOption.TCP_NODELAY, true)
				.childHandler(new ChannelInitializer<Channel>() {
					@Override
					protected void initChannel(Channel channel) throws Exception {
						/**
						 * 依次添加A、B、C三个outbound处理器
						 */
						channel.pipeline().addLast(new ChannelOutboundHandlerA());
						channel.pipeline().addLast(new ChannelOutboundHandlerB());
						channel.pipeline().addLast(new ChannelOutboundHandlerC());
					}
				});
		try {
			ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
			channelFuture.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
}

class ChannelOutboundHandlerA extends ChannelOutboundHandlerAdapter {
	
	@Override
	public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
		System.out.println("ChannelOutboundHandlerA:" + msg);
		ctx.writeAndFlush(msg);
	}
}

class ChannelOutboundHandlerB extends ChannelOutboundHandlerAdapter {
	@Override
	public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
		System.out.println("ChannelOutboundHandlerB:" + msg);
		ctx.write(msg);
	}
	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		ctx.executor().schedule(new Runnable() {
			@Override
			public void run() {
				ctx.channel().pipeline().write("china");
			}
		}, 3, TimeUnit.SECONDS);
	}
}

class ChannelOutboundHandlerC extends ChannelOutboundHandlerAdapter {

	@Override
	public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
		System.out.println("ChannelOutboundHandlerC:" + msg);
		ctx.write(msg);
	}
}
